#!/bin/bash
#!-*- sh -*-
#
# Abs: getRdb gets data out of a relational database 
#
# Rem: Specifically, getRdb uses the client side of the rdbService. rdbService is an
#      example EPICS V4 service, for getting data from a relational database such
#      as Oracle. The Oracle interactions are coded to persistently try to get data
#      should a first attempt fail. 
#
#      getRdb calls rdbClient client side RPC calls the rdbService side over pvAccess.
#
# Use: getRdb name-of-query-understood-by-your-server
# 
#         > ./getRdb name-of-query-understood-by-your-server
#
#      E.g.: 
#         bash-3.2$ ./getRdb LCLS:elementInfo.byZ
# 
# Ref: <TODO>
# ----------------------------------------------------------------------------
# Auth: 13-Oct-2011, Greg White (greg@slac.stanford.edu)
# Mod:  
# ============================================================================
BADARGS=1

function usage {
    echo "
    getRdb is a utility for getting data out of a relational database.
 
    Usage: getRdb [-lLrch] queryname
   
   -h   Show this help
   -l   Print labels as well as data. This is the default
   -L   No labels are printed, useful in unix pipes
   -r   Print output row oriented
   -c   Print output column oriented (ie as a table). This is the default
    
   The database queries understood by getRdb are each 'named' so a user does not
   have to know the SQL query itself, only the name of the query. The SQL queries
   equivalent to each name, are known by the server that getRdb calls. As a user,
   you only have to know the simple names.
   
   Examples:
       Note: the names of queries will change from lab ot lab, so these examples
       from PSI are for illustration.
       
       At PSI this gets all the devices of the SwissFEL accelerator and associated 
       information about them:
       
       $ getRdb swissfeltest:alldevices  
      
       This might get all of the modelled Twiss parameters of every element
       the last time the model was run on the real machine:
       
       $ getRdb  modelTwiss:Extant.FullMachine
       
       To suppress labels, use -L:
       
       % getRdb -L swissfel:sectiontree 
       
"
}   

source `dirname $0`/rdb_setup.bash

labelswanted=labels
orientation=col
while getopts Llrch opt; do
    case $opt in
        h) usage; shift ;;
        l) labelswanted=labels; shift ;;
        L) labelswanted=nolabels; shift ;;
        r) orientation=row; shift ;;
        c) orientation=col; shift ;;
        *) printf "option not recognized. Try getRdb -h for help\n"; exit $BADARGS;;
    esac
done

if [ $# -le 0 ]; then 
    echo "getRdb requires the name of a query to be given. Try getRdb -h for help."
    exit 1
fi

./rdbClientRunner $1 $orientation $labelswanted

exit $?
